package legumes.shared.domain;

public enum Unit {
	G("G"), KG("KG"), CL("cl"), L("L"), UNITY("Pièce");

	// In database, this is the toString() that is stored.
	// For MMI, this is getDisplayName() that is displayed.

	/** main display name */
	private String displayName;
	/** other display names */
	private String[] displayNames;

	public static Unit fromDisplayName(String displayName_) {
		for (Unit r : values()) {
			if (r.isValidDisplayName(displayName_)) {
				return r;
			}
		}
		return null;
	}

	public boolean isValidDisplayName(String s_) {
		if (displayName.equals(s_)) {
			return true;
		}

		for (String displayName : displayNames) {
			if (displayName.equalsIgnoreCase(s_)) {
				return true;
			}
		}
		return false;
	}

	private Unit(String displayName_, String... displayNames_) {
		displayName = displayName_;
		displayNames = displayNames_;
	}

	public float convertTo(float f_, Unit toUnit_) {
		switch (this) {
		case G:
			switch (toUnit_) {
			case G:
				return f_;
			case KG:
				return f_ / 1000f;
			}
		case KG:
			switch (toUnit_) {
			case G:
				return f_ * 1000f;
			case KG:
				return f_;
			}
		case L:
			switch (toUnit_) {
			case L:
				return f_;
			}
		case UNITY:
			switch (toUnit_) {
			case UNITY:
				return f_;
			}
		}
		throw new IllegalArgumentException("Impossible to convert from " + this
				+ " to " + toUnit_);
	}

	public String[] getSubUnitsDisplayNames() {
		switch (this) {
		case G:
			return new String[] { KG.getDisplayName(), G.getDisplayName() };
		case KG:
			return new String[] { KG.getDisplayName(), G.getDisplayName() };
		case L:
			return new String[] { L.getDisplayName(), CL.getDisplayName() };
		case CL:
			return new String[] { L.getDisplayName(), CL.getDisplayName() };
		case UNITY:
			return new String[] { UNITY.getDisplayName() };
		}
		return null;
	}

	public boolean isUnity() {
		return equals(UNITY);
	}

	public boolean isVolume() {
		return this.equals(L);
	}

	public boolean isWeight() {
		return this.equals(KG) || this.equals(G);
	}

	public String getDisplayName() {
		return displayName;
	}

	public static String [] getAllDisplaynames(){
		return new String []{
				KG.getDisplayName(), G.getDisplayName(),
				L.getDisplayName(), CL.getDisplayName(),
				UNITY.getDisplayName()
		};
	}
	
	public static String getAllDisplaynamesAsString(){
		StringBuffer sb = new StringBuffer();
		String sep = ", ";
		for(String s : getAllDisplaynames()){
			sb.append(s);
			sb.append(sep);
		}
		return sb.substring(0, sb.length()-sep.length());
	}
}
